<script setup name="AsDatePicker">
  // 该组件用于搭配vxe-table使用
  // 以对el-date-picker变量与事件进行透传(多数情况下组件可复用, 直接在组件上使用el-date-picker的属性与事件即可)
  // !注意插槽与ref未作处理, 若业务复杂, 使用el-date-picker自行处理
  import { ref, computed, watch } from 'vue'
  const props = defineProps({
    column: {
      type: Object,
      default: () => [],
    },
    iconWidth: {
      type: Number,
      default: 0,
    },
    comWidth: {
      type: Number,
      default: 0,
    },
    teleported: {
      type: Boolean,
      default: false,
    },
    // 'year' | 'month' | 'date' | 'datetime' | 'week' | 'datetimerange' | 'daterange'
    type: {
      type: String,
      default: 'datetimerange',
    },
    // 选择完后是否立即触发事件
    immediate: {
      type: Boolean,
      default: true,
    },
  })

  const asValue = ref(props.column)
  watch(
    () => props.column,
    (newValue, oldValue) => {
      asValue.value = newValue
    },
    {
      immediate: true,
      deep: true,
    }
  )

  const emit = defineEmits(['change'])

  const handleFilterChangeEvent = (params) => emit('change', params, props.immediate)

  const styleEl = computed(() => ({ display: 'inline-block', width: `calc(100% - ${props.iconWidth}px)` }))

  const typeMap = {
    year: 'YYYY',
    month: 'YYYY-MM',
    date: 'YYYY-MM-DD',
    datetime: 'YYYY-MM-DD HH:mm:ss',
    week: 'YYYY-WW',
    datetimerange: 'YYYY-MM-DD HH:mm:ss',
    daterange: 'YYYY-MM-DD',
  }

  const valueFormat = computed(() => typeMap[props.type])
</script>

<template>
  <div :style="styleEl">
    <el-date-picker
      clearable
      :type="type"
      v-bind="$attrs"
      v-model="column.filters[0].data"
      :value-format="valueFormat"
      @change="handleFilterChangeEvent(column.filters[0])"
      :style="{ width: `calc(100% - ${comWidth}px)` }"
    ></el-date-picker>
  </div>
</template>
